import { old_testament, new_testament } from "./bibleIndices.js";

function* chapter_generator(full_title, zhang, capacity, backward = false) {
    // 选择新约或旧约
    // const testament = old_testament.hasOwnProperty(full_title) ? old_testament : new_testament
    const testament = old_testament.has(full_title) ? old_testament : new_testament
    const zhangsOfChapter = testament.get(full_title)[1]
    if (zhang > zhangsOfChapter) {
        zhang = zhangsOfChapter
    }
    // 储存每日读经的章节数
    let chapter_list = [] // for yield
    let zhang_list = []
    let count = 0
    let locate_start_point = true

    while (true) {
        const all_keys = backward ? [...testament.keys()].reverse() : testament.keys()
        for (let k of all_keys) {
            let [short_title, num] = testament.get(k)

            let start = backward ? num : 1
            let stop = backward ? 0 : num + 1
            let step = backward ? -1 : 1
            for (let i = start; i != stop; i += step) {
                if (locate_start_point) {
                    if (k != full_title) break
                    else if (i == zhang) locate_start_point = false
                    else continue
                }
                zhang_list.push(i)
                count++
                if (count == capacity) {
                    chapter_list.push([k, short_title, zhang_list])
                    yield chapter_list
                    chapter_list = []
                    zhang_list = []
                    count = 0
                }
            }
            if (zhang_list.length) {
                chapter_list.push([k, short_title, zhang_list])
                zhang_list = []
            }
        }
    }
}

function fmt_to_str(chapter) {
    const str_array = []
    for (let [, title, zhangs] of chapter) {
        str_array.push(zhangs.length > 1 ? `${title}${zhangs.at(0)}~${zhangs.at(-1)}` : `${title}${zhangs.at(0)}`)
    }
    return str_array.join(', ')
}

// function get_chapter_info(full_title = '创世记', zhang = 1, capacity = 2, days = 7, skip = 0) { }
export default function schedule_per_week({ full_title = '创世记', zhang = 1, capacity = 3, days = 7 } = {}) {
    const gen = chapter_generator(full_title, zhang, capacity)
    const data = []
    for (let i = 0; i < days; i++) {
        data.push(fmt_to_str(gen.next().value))
    }
    return data
}

// console.log(schedule_per_week({ full_title: '约翰一书' }))